<template>
  <div class="login">
    <el-container>
      <el-header class="header-wrap">
        <div class="header">
          <h1>通用管理系统</h1>
          <span>欢迎您的登录</span>
        </div>
      </el-header>
      <el-main class="main-wrap">
        <div class="main">
          <el-card class="box-card">
            <el-tabs v-model="activeName" stretch class="demo-tabs">
              <el-tab-pane label="登录" name="first">
                <el-form :model="loginData" label-width="60px">
                  <el-form-item label="账户">
                    <el-input v-model="loginData.account" placeholder="账户" />
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input v-model="loginData.password" placeholder="密码" />
                  </el-form-item>

                  <el-form-item label="验证码" prop="code">
                    <el-input
                      v-model="loginData.code"
                      auto-complete="off"
                      placeholder="验证码"
                      style="width: 63%"
                    ></el-input>
                    <div class="login-code">
                      <div v-html="src" @click="getCode" class="login-code-img"></div>
                    </div>
                  </el-form-item>
                </el-form>
                <el-link
                  type="primary"
                  style="float:right;font-size:12px;"
                  @click="dialogVisible = true"
                >忘记密码</el-link>
                <el-button
                  type="primary"
                  style="width:100%"
                  @click="toLogin()"
                  :loading="loginLoading"
                >登录</el-button>
              </el-tab-pane>
              <el-tab-pane label="注册" name="second">
                <el-form :model="registerData" label-width="70px">
                  <el-form-item label="账户">
                    <el-input v-model="registerData.account" placeholder="账户" />
                  </el-form-item>
                  <el-form-item label="密码">
                    <el-input v-model="registerData.password" placeholder="密码" />
                  </el-form-item>
                  <el-form-item label="重复密码">
                    <el-input v-model="registerData.rPassword" placeholder="密码" />
                  </el-form-item>
                  <el-form-item label="手机号">
                    <el-input v-model="registerData.phone" placeholder="手机号" />
                  </el-form-item>
                  <el-form-item label="验证码">
                    <el-input v-model="registerData.code" placeholder="验证码" />
                    <el-button
                      v-if="isSHOWCode"
                      class="code"
                      type="primary"
                      @click="toSend()"
                      :loading="sendLoading"
                    >获取验证码</el-button>
                    <el-countdown
                      v-else
                      format="ss"
                      :value="value1"
                      @finish="toFinish"
                      :value-style="{
                        'font-size':'12px',
                        'margin-left': '10px'
                      }"
                    >
                      <template #suffix>s 从新获取</template>
                    </el-countdown>
                  </el-form-item>
                </el-form>

                <el-button
                  type="primary"
                  style="width:100%"
                  @click="toRegister()"
                  :loading="registerLoading"
                >注册</el-button>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </div>
      </el-main>
      <el-footer>
        <div class="footer">
          <span>连接</span> |
          <span>连接</span> |
          <span>连接</span> |
          <span>连接</span>
        </div>
      </el-footer>
    </el-container>
    <el-dialog draggable v-model="dialogVisible" title="忘记密码" width="400px">
      <el-form ref="forgetRef" :rules="forgetRules" :model="forget" label-width="60px">
        <el-form-item label="账户" prop="account">
          <el-input v-model="forget.account" placeholder="账户" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forget.email" placeholder="邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="next()">下一步</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog draggable v-model="dialogVisible1" title="重置密码" width="400px">
      <el-form ref="resettingRef" :rules="resettingRules" :model="resetting" label-width="70px">
        <el-form-item label="密码">
          <el-input v-model="resetting.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="重复密码">
          <el-input v-model="resetting.rPassword" placeholder="重复密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="toReset()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import {
  register,
  login,
  verify,
  resetPassword,
  getCaptcha,
  sendCode
} from "@/api/login";
import { addLoginLog } from "@/api/log";

import { ref, reactive, onMounted } from "vue";

import { useRouter } from "vue-router";
const router = useRouter();

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import { ElMessage } from "element-plus";
const activeName = ref("first");
const loginData = reactive({
  account: "",
  password: "",
  code: "",
  uuid: ""
});
const loginLoading = ref(false);
const toLogin = () => {
  if (!loginData.account) {
    return ElMessage.error("请填写账户");
  }
  if (!loginData.password) {
    return ElMessage.error("请填写密码");
  }
  if (!loginData.code) {
    return ElMessage.error("请填写验证码");
  }

  let data = {
    account: loginData.account,
    password: loginData.password,
    code: loginData.code,
    uuid: loginData.uuid
  };
  loginLoading.value = true;
  login(data)
    .then(async res => {
      if (res.data.status != 0) {
        getCode();
        return ElMessage.error(res.data.message);
      }
      ElMessage.success(res.data.message);
      localStorage.setItem("token", res.data.token);
      localStorage.setItem("name", res.data.data.name);
      store.dispatch("getUserInfo");
      let queryData = {
        account: res.data.data.account,
        name: res.data.data.name,
        email: res.data.data.email
      };
      await addLoginLog(queryData);
      router.replace({
        path: "/home"
      });
    })
    .finally(() => {
      loginLoading.value = false;
    });
};

const registerData = reactive({
  account: "",
  password: "",
  rPassword: "",
  phone: "",
  code: ""
});
const registerLoading = ref(false);
const toRegister = () => {
  if (!registerData.account) {
    return ElMessage.error("请填写账户");
  }
  if (!registerData.password) {
    return ElMessage.error("请填写密码");
  }
  if (registerData.password != registerData.rPassword) {
    return ElMessage.error("两次输入的密码不一样");
  }
  if (!registerData.phone) {
    return ElMessage.error("请填写手机号");
  }
  if (!registerData.code) {
    return ElMessage.error("请填写验证码");
  }
  let data = {
    account: registerData.account,
    password: registerData.password,
    phone: registerData.phone,
    code: registerData.code
  };

  registerLoading.value = true;
  register(data)
    .then(res => {
      console.log(res);
      if (res.data.status != 0) {
        return ElMessage.error(res.data.message);
      }
      ElMessage.success(res.data.message);
      activeName.value = "first";
    })
    .finally(() => {
      registerLoading.value = false;
    });
};

const dialogVisible = ref(false);
const forget = reactive({
  account: "",
  email: ""
});

const dialogVisible1 = ref(false);
const resetting = reactive({
  password: "",
  rPassword: ""
});

const forgetRules = reactive({
  account: [{ required: true, message: "请填写账户", trigger: "blur" }],
  email: [{ required: true, message: "请填写邮箱", trigger: "blur" }]
});
const id = ref("");
const forgetRef = ref();
const next = () => {
  forgetRef.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      let data = {
        account: forget.account,
        email: forget.email
      };
      verify(data).then(res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        id.value = res.data.id;
        ElMessage.success(res.data.message);
        dialogVisible.value = false;
        dialogVisible1.value = true;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resettingRules = reactive({
  password: [{ required: true, message: "请填写密码", trigger: "blur" }],
  rPassword: [{ required: true, message: "请填写密码", trigger: "blur" }]
});
const resettingRef = ref();
const toReset = () => {
  if (resetting.password != resetting.rPassword) {
    return ElMessage.error("两次输入的密码不一样");
  }
  resettingRef.value.validate((valid, fields) => {
    if (valid) {
      let data = {
        id: id.value,
        password: resetting.password
      };
      resetPassword(data).then(res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        ElMessage.success(res.data.message);
        dialogVisible.value = false;
        dialogVisible1.value = false;
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const src = ref();
const getCode = e => {
  // e.target.src = `http://127.0.0.1:7001/user/getCaptcha?${Math.random()}`;
  getCaptcha().then(res => {
    src.value = res.data.img;
    loginData.uuid = res.data.uuid;
  });
};
const value1 = ref(Date.now() + 1000 * 60);
const sendLoading = ref(false);
const toFinish = () => {
  value1.value = Date.now() + 1000 * 60;
  isSHOWCode.value = true;
};
const isSHOWCode = ref(true);
const toSend = () => {
  let mobileReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  console.log(mobileReg, mobileReg.test(registerData.phone));
  if (mobileReg.test(registerData.phone) == false) {
    return ElMessage.error("手机号格式错误");
  }

  let data = {
    phone: registerData.phone
  };
  sendLoading.value = true;
  sendCode(data)
    .then(res => {
      if (res.data.status != 0) {
        return ElMessage.error(res.data.message);
      }
      isSHOWCode.value = false;
      ElMessage.success(res.data.message);
    })
    .finally(() => {
      sendLoading.value = false;
    });
};
//声明周期函数，自动执行初始化
onMounted(() => {
  getCode();
});
</script>

<style scoped lang="scss">
.login {
  // background: RED;
}
.el-form-item {
  display: flex;
  .el-input {
    flex: 1;
  }
}
.header-wrap {
  .header {
    width: 1200px;
    height: 100%;
    margin: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    h1 {
      font-size: 20px;
      font-weight: bold;
    }
  }
}
.main-wrap {
  height: 600px;
  background: url("@/assets/login/bg.jpg") center;
  background-size: cover;
  .main {
    position: relative;
    width: 1200px;
    height: 100%;
    margin: auto;
    .box-card {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 300px;
      height: 400px;
    }
  }
}
.footer {
  width: 1200px;
  margin: auto;
  text-align: center;
  padding-top: 10px;
  span {
    margin: 20px;
    cursor: pointer;
  }
}
.login-code {
  width: 36.9%;
  height: 32px;
  background: #cc9966;
  .login-code-img {
    width: 100%;
    height: 32px;
    svg {
      width: 100%;
    }
  }
}
::v-deep .el-statistic__suffix {
  font-size: 14px;
}
</style>